package com.example.bigevent.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.bigevent.pojo.Result;
import com.example.bigevent.utils.JwtUtils;
import com.example.bigevent.utils.ThreadLocatUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 登录检查
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求地址
        String url = request.getRequestURI().toString();
        // 判断是否是 login 路径
        if (url.contains("login")) {
            // 放行操作
            return true;
        }

        // 获取请求头中的 token 信息
        String jwt = request.getHeader("token");
        // 判断 token 信息是否为空
        if (!StringUtils.hasLength(jwt)) {
            Result error = Result.error("NOT_LOGIN");
            // 对象 --> json
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        // 校验 token 信息
        try {
            // 从 redis 中取出 jwt
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(jwt);
            if (redisToken == null) {
                throw new RuntimeException();
            }
            Map<String, Object> cliams = JwtUtils.parseJWT(jwt);
            ThreadLocatUtil.set(cliams);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN");
            // 对象 --> json
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{
        ThreadLocatUtil.remove();
    }
}
